package com.tanhua.api.mongo;

import com.tanhua.mongo.FollowUser;
import com.tanhua.mongo.Video;
import com.tanhua.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;

    public PageBeanVo findVideo(Integer page, Integer pagesize) {

        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Video> list = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);

        return new PageBeanVo(page,pagesize,count,list);
    }

    @Override
    public void save(Video video) {
        video.setVid(idService.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(video);
    }

    @Override
    public void guanzhu(FollowUser followUser) {
        mongoTemplate.insert(followUser);
    }

    @Override
    public void unguanzhu(Long followUserId, Long userId) {

        Query query = new Query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
        mongoTemplate.remove(query,FollowUser.class);
    }

    @Override
    public PageBeanVo findVideos(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        Long count= mongoTemplate.count(query, Video.class);
        return new PageBeanVo(page,pagesize,count,videoList);
    }
}
